<template>
  <base-breadcrumb :title="titleName">
    <searchData
      v-show="activeKey === 'audit'"
      :search-data="searchArr"
      @search="search"
    />
    <searchData
      v-show="activeKey === 'business'"
      :search-data="searchBusinessArr"
      @search="handleSearchBusiness"
    />
    <a-card :bordered="false">
      <a-tabs v-model="activeKey">
        <a-tab-pane key="audit">
          <template slot="tab">
            <a-badge
              :count="tipCountInfo.audit || 0"
              :number-style="{ backgroundColor: '#F59A23' }"
              :offset="[6, 0]"
            >
              <span>审批待办</span>
            </a-badge>
          </template>
          <div>
            <a-button
              type="primary"
              @click="batchApproval"
              style="margin-bottom: 10px"
            >批量审批</a-button>
            <div class="pub-table-select-count">
              <a-icon
                type="info-circle"
                theme="twoTone"
              />
              <span style="margin-right: 12px">
                待审批事项：<span class="totalNum">{{ tipCountInfo.audit || 0 }} 个</span>
              </span>
            </div>

            <list-table
              ref="table"
              row-key="taskId"
              :columns="columns"
              :request="loadData"
              :alert="true"
              :selectConfig="{ use: true, type: 'checkbox', rowKey: 'id' }"
              @select-click="selectClick"
            >
              <!-- <span slot="serial" slot-scope="text, record, index">{{ index + 1 }}</span> -->
              <template
                slot="serial"
                slot-scope="text, record, index"
              >
                <div style="display: flex">
                  <a-tag
                    style="float: left"
                    v-if="record.urge"
                    color="#F59A23"
                  >加急</a-tag> {{ index + 1 }}
                </div>
              </template>
              <template
                slot="status"
                slot-scope="text, record"
              >
                <a-badge
                  v-if="isNeedReslove(record.businessType)"
                  :status="text | statusTypeFilter"
                  :text="'待处理'"
                />
                <a-badge
                  v-else
                  :status="text | statusTypeFilter"
                  :text="text | statusFilter"
                />
              </template>
              <template
                slot="taskSource"
                slot-scope="text"
              >
                <ellipsis
                  :length="8"
                  tooltip
                >
                  {{ text | taskSourceFilter }}
                </ellipsis>
              </template>
              <template
                slot="description"
                slot-scope="text"
              >
                <ellipsis
                  :length="8"
                  tooltip
                >
                  {{ text }}
                </ellipsis>
              </template>
              <template
                slot="action"
                slot-scope="text, record"
              >
                <a
                  v-if="isNeedReslove(record.businessType)"
                  @click="handle(record)"
                >处理</a>
                <a
                  v-else
                  @click="handle(record)"
                >
                  {{ actionMap[record.taskType] }}
                </a>
              </template>
            </list-table>
            <!-- <pagination
              v-model="pageNo"
              :total="totalSize"
              :page-size.sync="pageSize"
              @change="handlePageChange"
              @showSizeChange="showSizeChange"
            /> -->
          </div>
        </a-tab-pane>
        <a-tab-pane key="business">
          <template slot="tab">
            <a-badge
              :count="tipCountInfo.business"
              :number-style="{ backgroundColor: '#F59A23' }"
              :offset="[6, 0]"
            >
              <span>业务待办</span>
            </a-badge>
          </template>
          <BusinessTodo
            ref="BusinessTodo"
            :show-count="true"
            :search-query="childQuery"
          />
        </a-tab-pane>
      </a-tabs>
    </a-card>
  </base-breadcrumb>
</template>

<script>
import { Ellipsis } from '@/components'
import { getTodoList, getTodoTotal,tranferBath} from '@/api/process'
import { getProcessParams, getBusinessTodoList } from '@/api/commons'
import { BUSINESS_SOURCE_MAP } from '@/config/businessConfig.js'
import { handleAuditInList } from '@/utils/util'
import OrgTreeSelect from '@/components/TreeSelect'

import Vue from 'vue'
import BusinessTodo from './BusinessTodo.vue'

const searchBusinessArr = [
  {
    name: '标题',
    value: 'noticeTitle',
    type: 'input'
  },
  {
    name: '内容',
    value: 'noticeContent',
    type: 'input'
  }
]

const searchArr = [
  // 搜索框
  {
    name: '事项名称',
    value: 'processName',
    type: 'input'
  },
  {
    name: '事项来源',
    value: 'taskSource',
    type: 'select',
    data: Object.keys(BUSINESS_SOURCE_MAP).map((key) => {
      return {
        label: BUSINESS_SOURCE_MAP[key],
        value: key
      }
    })
  },
  {
    name: '状态',
    value: 'taskType',
    type: 'select',
    data: [
      {
        label: '待审批',
        value: '1'
      },
      {
        label: '待处理',
        value: '2'
      },
      {
        label: '待会签',
        value: '3'
      }
    ]
  },
  {
    name: '关键信息',
    value: 'keyword',
    type: 'input'
  },
  {
    name: '发起单位',
    valueKey: 'startOrgName',
    type: OrgTreeSelect,
    attrs: {
      isNeedOrgId: true,
      needTags: []
    }
  }
]

const columns = [
  {
    title: '序号',
    width: '65px',
    customize:true,
    scopedSlots: { customRender: 'serial' }
  },
  {
    title: '事项名称',
    dataIndex: 'processName'
  },
  {
    title: '事项来源',
    dataIndex: 'taskSource',
    scopedSlots: { customRender: 'taskSource' }
  },
  {
    title: '发起人',
    dataIndex: 'startUserName'
  },
  {
    title: '发起单位',
    dataIndex: 'startOrgName'
  },
  {
    title: '关键信息',
    dataIndex: 'keyword'
  },
  {
    title: '当前节点',
    dataIndex: 'taskName'
  },
  {
    title: '当前滞留时间',
    dataIndex: 'durationInMillis'
  },
  {
    title: '状态',
    dataIndex: 'taskType',
    width: '110px',
    scopedSlots: { customRender: 'status' }
  },
  {
    title: '操作',
    dataIndex: 'action',
    width: '180px',
    fixed: 'right',
    scopedSlots: { customRender: 'action' }
  }
]

const statusMap = {
  1: { text: '待审批', status: 'warning' },
  2: { text: '待处理', status: 'processing' },
  3: { text: '待签名', status: 'processing' }
}

const taskSourceMap = BUSINESS_SOURCE_MAP

export default {
  name: 'TodoTableList',
  components: {
    Ellipsis,
    BusinessTodo
  },
  filters: {
    statusFilter(type) {
      return statusMap[type] && statusMap[type].text
    },
    statusTypeFilter(type) {
      return statusMap[type] && statusMap[type].status
    },
    taskSourceFilter(type) {
      return taskSourceMap[type]
    }
  },
  data() {
    return {
      tipCountInfo: {
        // 待办数统计提示
        audit: 0,
        business: 0
      },
      childQuery: {}, // 子级参数
      searchBusinessArr,
      activeKey: 'audit',
      loading: true,
      columns,
      actionMap: {
        1: '审批',
        2: '处理',
        3: '签名'
      },
      searchArr,
      titleName: '',

      // 高级搜索 展开/关闭
      advanced: false,
      // 查询参数
      queryParam: {},
      // 加载数据方法 必须为 Promise 对象
      selectedRowKeys: [],
      selectedRows: [],
      totalDels: {
        auditNum: 0,
        solveNum: 0,
        signNum: 0
      },
      tableData: [],
      totalSize: 1,
      pageNo: 0,
      pageSize: 10,
      currentUser: {},
      timer: null,
      timerLong: 30000,

      isPage: false,
      usersIds: [],
      loadData: (parameter) => {
        const userInfo = Vue.getAcloudProvider().getUserInfo()
        if (!this.isPage) return false
        const requestParameters = Object.assign(parameter, this.queryParam, { users: this.usersIds })
        return getTodoList(requestParameters).then((res) => {
          //特殊流程禁用
          res.data.length &&
            res.data.map((item) => {
              item.disabled = item.specialTask
            })
          // this.tableData = res1.data
          this.totalSize = res.totalSize
          let count = isNaN(Number(this.totalSize)) ? 0 : Number(this.totalSize)
          this.$store.commit('messageInfo/SET_TODOCOUNT', count)
          this.tipCountInfo.audit = count || 0 // 审批待办数量
          // 业务待办
          getBusinessTodoList({ query: { receiverId: userInfo.id, status: 0 } }).then((res) => {
            const totalNum = res.totalSize + count
            this.$store.commit('messageInfo/SET_TODOCOUNT', totalNum)
            this.tipCountInfo.business = res.totalSize || 0 // 业务待办数量
          })
          this.destoryTimer()
          this.timer = setTimeout(() => {
            this.getTodoTotal()
          }, this.timerLong)

          return res
        })
      },
      selectedRowKeysArr: [], //选中的数据
      // 登录人信息
      info: Vue.getAcloudProvider().getUserInfo(),
      tranferBathData:[],

    }
  },
  computed: {
    rowSelection() {
      return {
        selectedRowKeys: this.selectedRowKeys,
        selectedRows: this.selectedRows, // 当前行所有数据
        onChange: this.onSelectChange
      }
    }
  },
  created() {
    this.initPage()
    this.currentUser = Vue.getAcloudProvider().getUserInfo()
    // this.list()
    this.getByEmployeeUser()
    this.initMessageListener()
    this.getTodoTotal()
  },
  beforeDestroy() {
    this.destoryTimer()
  },
  methods: {
    selectClick(data, str) {
      this.selectedRowKeysArr = data.rows
    },
    //批量逻辑处理
    batchApproval() {
      let selectedRowKeysArrLen = this.selectedRowKeysArr.length
      if (0 < selectedRowKeysArrLen * 1 && selectedRowKeysArrLen * 1 <= 10) {
       this.batchApprovalSetData();
      } else if (selectedRowKeysArrLen > 10) {
        this.$message.warning('最多只能选中10条数据')
      } else {
        this.$message.warning('请至少选择一条数据')
      }
    },
    //批量审批查看数据是否被转办
    batchApprovalSetData(){
      const { id: userId } = this.info;
      let req = [];
      this.tranferBathData = []
      this.selectedRowKeysArr.map((item)=>{
          req.push({
            userId:userId,
            taskId:item.taskId 
          })
      })
      tranferBath(req).then((res) => {
        if (res.code === this.SUCCESS_CODE) {
          this.tranferBathData = res.data;
           this.selectedRowKeysArr.map((item)=>{
            Object.keys(this.tranferBathData).map((tItem)=>{
              if(tItem == item.taskId){
                  item.isTranfter =this.tranferBathData[tItem]; //设置是否隐藏转办
                  item.reject=1; //设置默认值
                  localStorage.setItem('approvalArr', JSON.stringify(this.selectedRowKeysArr))
              }
            })
         })
        }
      })
      handleAuditInList.call(this, this.selectedRowKeysArr[0], true) //默认显示第一个数据
    
    },
    initPage() {
      if (this.$route.query.tabKey) {
        this.activeKey = this.$route.query.tabKey
      }
    },
    isNeedReslove(businessType) {
      const whiteList = ['1007', '1008']
      return whiteList.includes(businessType)
    },

    async getByEmployeeUser() {
      const userInfo = Vue.getAcloudProvider().getUserInfo()
      // 查询参数限制权限为账号所有的岗位及登录用户id
      if (userInfo?.employee?.posts) {
        this.usersIds = this.usersIds.concat(userInfo.employee.posts.map((item) => item.id))
      }
      this.usersIds.push(this.currentUser.id)
      let processRes = {}
      try {
        processRes = await getProcessParams()
      } catch (e) {
        console.error(e)
      }
      if (processRes.data) {
        this.usersIds = this.usersIds.concat(processRes.data)
      }
      this.isPage = true
      this.$refs.table.refresh(true)
    },
    /**
     * 业务待办搜索
     */
    handleSearchBusiness(val = {}) {
      this.childQuery = {
        ...val
      }
      this.$nextTick(() => {
        this.$refs.BusinessTodo.refreshTable()
      })
    },
    async getTodoTotal() {
      try {
        const userInfo = Vue.getAcloudProvider().getUserInfo()
        let users = []
        // 查询参数限制权限为账号所有的岗位及登录用户id
        if (userInfo?.employee?.posts) {
          users = users.concat(userInfo.employee.posts.map((item) => item.id))
        }
        users.push(userInfo.id)
        let processRes = {}
        try {
          processRes = await getProcessParams()
        } catch (e) {
          console.error(e)
        }
        if (processRes.data) {
          users = users.concat(processRes.data)
        }
        const params = {
          users: users
        }
        const res = await getTodoTotal(params)
        if (res.code === 200) {
          const map = {
            1: 'auditNum',
            2: 'solveNum',
            3: 'signNum'
          }
          const list = res.data || []
          list.forEach((item) => {
            if (map[item.task_type]) {
              this.totalDels[map[item.task_type]] = item.nums || 0
            }
          })
        }
      } catch (e) {
        console.error(e)
      }
    },
    initMessageListener() {
      const handler = (e) => {
        const fromOrigin = e.origin || e.originalEvent.origin
        if (fromOrigin === window.location.origin) {
          // 验证是否同源，避免第三方攻击
          if (e.data === 'finish') {
            // 验证完成标志
            this.$refs.table.refresh(true)
          }
        }
      }
      window.addEventListener('message', handler, false)
      this.$once('hook:beforeDestroy', () => {
        window.removeEventListener('message', handler)
      })
    },
    // 清除定时器
    destoryTimer() {
      if (this.timer === null) return
      clearTimeout(this.timer)
      this.timer = null
    },
    async list(parameter, callback) {
      this.loading = true
      try {
        let users = []
        const userInfo = Vue.getAcloudProvider().getUserInfo()
        // 查询参数限制权限为账号所有的岗位及登录用户id
        if (userInfo?.employee?.posts) {
          users = users.concat(userInfo.employee.posts.map((item) => item.id))
        }
        users.push(this.currentUser.id)
        let processRes = {}
        try {
          processRes = await getProcessParams()
        } catch (e) {
          console.error(e)
        }
        if (processRes.data) {
          users = users.concat(processRes.data)
        }
        const requestParameters = Object.assign(
          {
            pageSize: callback ? this.totalSize : this.pageSize,
            pageNo: this.pageNo
          },
          parameter,
          this.queryParam,
          { users }
        )
        let res1 = await getTodoList(requestParameters)
        this.tableData = res1.data
        this.totalSize = res1.totalSize
        let count = isNaN(Number(this.totalSize)) ? 0 : Number(this.totalSize)
        this.$store.commit('messageInfo/SET_TODOCOUNT', count)
        this.tipCountInfo.audit = count || 0 // 审批待办数量
        // 业务待办
        getBusinessTodoList({ query: { receiverId: userInfo.id, status: 0 } }).then((res) => {
          const totalNum = res.totalSize + count
          this.$store.commit('messageInfo/SET_TODOCOUNT', totalNum)
          this.tipCountInfo.business = res.totalSize || 0 // 业务待办数量
        })
        this.destoryTimer()
        this.timer = setTimeout(() => {
          this.getTodoTotal()
          this.list(parameter, callback)
        }, this.timerLong)
      } catch (e) {
        console.error(e)
      } finally {
        this.loading = false
      }
    },
    handlePageChange(pageNo) {
      this.pageNo = pageNo
      this.list()
    },
    showSizeChange(pageNo, pageSize) {
      this.pageNo = 1
      this.pageSize = pageSize
      this.list()
    },
    search(val) {
      this.queryParam = val
      // this.list()
      this.$refs.table.refresh(true)
    },
    handle(val) {
      if(val.businessType == '809'|| val.businessType == '810' || val.businessType == '811' || val.businessType == '812'){
        val.taskPcUrl = '/technical/ShiGroup/Approval/auditorApproval';
      }
      // console.log(val,2344)
      //val.businessType = '1007'
      localStorage.removeItem('approvalArr')
      handleAuditInList.call(this, val)
    },
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    }
  }
}
</script>
<style>
.rowBadge .ant-badge-status-dot {
  width: 10px;
  height: 10px;
  top: -2px;
}
</style>


